//
//  DeviceLocationVC.m
//  KEREN
//
//  Created by MW on 2023/3/30.
//

#import "DeviceLocationVC.h"

@interface DeviceLocationVC ()<MAMapViewDelegate>
@property (nonatomic, copy) NSString *locationStr;
@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, assign) CLLocationCoordinate2D location;
@property (nonatomic, assign) CGFloat longitude;
@property (nonatomic, assign) CGFloat latitude;

//目前所在地经纬度
@property (nonatomic, assign) CGFloat currentLatitude;
@property (nonatomic, assign) CGFloat currentLongitude;
@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) UILabel *pointLbl;
@end

@implementation DeviceLocationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavViewWithRightTitle:@"刷新" navColorIswhite:YES withTitle:@"车辆位置"];
    WEAKSELF
    self.rightClickBlock = ^(void){
        [weakSelf getDeviceLocation];
    };
    //    ///初始化地图
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 56 + STATUSBAR_HEIGHT, DEVICE_WIDTH, DEVICE_HEIGHT - 56 - STATUSBAR_HEIGHT)];
    _mapView.delegate = self;
    _mapView.zoomLevel = 12;
    ///把地图添加至view
    [self.view addSubview:_mapView];
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    _mapView.customizeUserLocationAccuracyCircleRepresentation = YES;
    
    [self bottomView];
    [self getDeviceLocation];
   // [self play_voice];
}


- (void)getDeviceLocation{
    WEAKSELF
    [NetworkingTool POST:Device_location parameters:@{@"ebike_id":@([UserInfoManager sharedInstance].currentDeviceInfo.Id),@"cmd":@"Location"} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            if([response[@"data"][@"lat"] floatValue] > 360){
                [[KRAlartManager shareInstance] showAlert:@"车辆位置获取失败"];
            }else{
                CLLocationCoordinate2D coor = [[GDMapTool sharedInstance] AMapCoordinateConvertWithLatitude:[response[@"data"][@"lat"] floatValue] andLongitude:[response[@"data"][@"lng"] floatValue]];
                MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
                weakSelf.latitude = [response[@"data"][@"lat"] floatValue];
                weakSelf.longitude = [response[@"data"][@"lng"] floatValue];

                pointAnnotation.coordinate = coor;
                //设置地图的定位中心点坐标
                weakSelf.mapView.centerCoordinate = coor;
                //将点添加到地图上，即所谓的大头针
                [weakSelf.mapView addAnnotation:pointAnnotation];
                [weakSelf setLocationWithLatitude:coor.latitude  AndLongitude:coor.longitude];
            }
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    if([annotation isKindOfClass:[MAUserLocation class]]){
        return nil;
    }

    //大头针标注
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {//判断是否是自己的定位气泡，如果是自己的定位气泡，不做任何设置，显示为蓝点，如果不是自己的定位气泡，比如大头针就会进
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAAnnotationView *annotationView = (MAAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil) {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.frame = CGRectMake(0, 0, 20, 24);
        annotationView.canShowCallout = YES;       //设置气泡可以弹出，默认为NO
        annotationView.draggable = YES;           //设置标注可以拖动，默认为NO
        annotationView.image = [UIImage imageNamed:@"point"];
        _rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 250, 0)];
        _rightButton.backgroundColor = [UIColor whiteColor];
        [_rightButton setTitleColor:Color_86898E forState:UIControlStateNormal];
        _rightButton.titleLabel.font = Font(14);
        _rightButton.titleLabel.numberOfLines = 0;
        annotationView.leftCalloutAccessoryView = _rightButton;

        return annotationView;
    }

    return nil;
}

- (void)setLocationWithLatitude:(CLLocationDegrees)latitude AndLongitude:(CLLocationDegrees)longitude{
     WEAKSELF
    CLLocation *location=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    CLGeocoder *geocoder=[[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error) {
            DDLogInfo(@"反编码失败:%@",error);
        }else{
            //NSLog(@"反编码成功:%@",placemarks);
            CLPlacemark *placemark=[placemarks lastObject];
            //NSLog(@"%@",placemark.addressDictionary[@"FormattedAddressLines"]);
            NSDictionary *addressDic=placemark.addressDictionary;
            NSString *state=[addressDic objectForKey:@"State"];
            NSString *city=[addressDic objectForKey:@"City"];
            NSString *subLocality=[addressDic objectForKey:@"SubLocality"];
            NSString *street=[addressDic objectForKey:@"Street"];
            NSString *name=[addressDic objectForKey:@"Name"];
            //NSLog(@"%@,%@,%@,%@",state,city,subLocality,street);
            NSString *strLocation;
            if (street.length == 0 || street == NULL || [street isEqualToString:@"(null)"]) {
                strLocation= [NSString stringWithFormat:@"%@%@%@%@",state,city,subLocality,name];
            }else{
                strLocation= [NSString stringWithFormat:@"%@%@%@%@%@",state,city,subLocality,street,name];
            }
            weakSelf.pointLbl.text = strLocation;
            [self.rightButton setTitle:strLocation forState:UIControlStateNormal];
        }
    }];
}

- (UIView *)bottomView{
    if(!_bottomView){
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, DEVICE_HEIGHT - BottomSpance_height - 100, DEVICE_WIDTH, 100 + BottomSpance_height)];
        _bottomView.layer.mask = [CAShapeLayer clipsToBounds:_bottomView.bounds Corners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(25, 25)];

        _bottomView.backgroundColor = Whire_Color;
        [UIView setLineViewWithframe:CGRectMake(0, 100, DEVICE_WIDTH, 1) forinView:_bottomView];
        UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(24, 10, 60, 60)];
        [icon sd_setImageWithURL:[NSURL URLWithString:[UserInfoManager sharedInstance].currentDeviceInfo.photo] placeholderImage:[UIImage imageNamed:@"devcie_defalaut_icon"]];
        [_bottomView addSubview:icon];
        UILabel *nameLbl = [UILabel setLblText:[UserInfoManager sharedInstance].currentDeviceInfo.name font:Font(24) withColor:Black_Color inSubView:_bottomView];
        [nameLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(icon.mas_right).offset(12);
            make.top.offset(20);
            make.right.offset(-100);
        }];
        _pointLbl = [UILabel setLblText:@"" font:Font(12) withColor:Color_86898E inSubView:_bottomView];
        [_pointLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(icon.mas_right).offset(12);
            make.top.equalTo(nameLbl.mas_bottom).offset(4);
            make.right.offset(-100);
        }];
        _pointLbl.numberOfLines = 0;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [_bottomView addSubview:button];
        [button setImage:[UIImage imageNamed:@"ponit_navgation"] forState:UIControlStateNormal];
        button.frame = CGRectMake(DEVICE_WIDTH - 72, 20, 58, 58);
        [button addTarget:self action:@selector(pointNavcation) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_bottomView];
    }
    return _bottomView;
}

- (void)pointNavcation{
    [self.view endEditing:YES];
    [[KRAlartManager shareInstance] showPointNavcation:_longitude latitude:_latitude pointName:@""];
}
@end
